﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NielsRask.K242.Core;
using System.Drawing;
using SdlDotNet.Graphics;
using NielsRask.K242.Core.AI;
using SdlDotNet.Graphics.Primitives;

namespace RenderTest1
{
	// vi får brug for at afkoble renderstack og oprettelsen af spilmodellen
	// der skal en ekstern kilde til at trigge updates af spilmodellen. denne viser kun modellen
	public class SectorRenderer
	{
		Sector sector;
		Size screenSize;
		Surface screen;
		Emperor emperor;
		public SectorRenderer( Sector sector, Emperor emperor )
		{
			this.sector = sector;
			this.emperor = emperor;
			screenSize = new Size( 800, 800 );
			screen = Video.SetVideoMode( screenSize.Width, screenSize.Height, 32, true, false, false );
			screen.Fill( new Rectangle( new Point( 0, 0 ), screenSize ), Color.BlueViolet );
		}

		public Surface Render()
		{
			screen.Fill( new Rectangle( new Point( 0, 0 ), screenSize ), Color.Black );
			lock ( sector )
			{
				foreach ( Asteroid asteroid in sector.Asteroids )
				{
					if ( asteroid.EmperorKnowledge.ContainsKey( emperor ) )
					{
						// render asteroiden
						//asteroid.Position
						//Console.WriteLine( "#" );
					}
					Circle c = new Circle( PositionToPoint( asteroid.Position ), ( short )8);
					if (asteroid.Colony != null)
						c.Draw( screen, Color.Red );
					else
						c.Draw( screen, Color.Cyan );
				}

				foreach ( Fleet fleet in sector.Fleets )
				{
					if ( fleet.Emperor == emperor )
					{
						// render flåden
					}
					Circle c = new Circle( PositionToPoint( fleet.Position ), ( short )3 );
					c.Draw( screen, Color.Magenta );
					// hvad med fjender? 
					// så skal vi for hver af dem loope emperor-fleets igennem og se om de er in range?

					Circle sensorRange = new Circle( PositionToPoint( fleet.Position ), ( short )StageLengthToScreenLength(fleet.SensorRange) );
					sensorRange.Draw( screen, Color.LightGray );

				}
			}
			screen.Update();

			return screen; //?
		}

		private Point PositionToPoint( PointF position )
		{
			// screensize er 800*600
			// stage er 100*100

			// ignorer ratio: pScreen.x = 800*pstage.x/100
			int x = ( int )( screenSize.Width * position.X / sector.Size.Width );
			int y = ( int )( screenSize.Height * position.Y / sector.Size.Height );
			return new Point( x, y );
		}

		private int StageLengthToScreenLength( float stageLength )
		{
			return ( int )( screenSize.Width * stageLength / sector.Size.Width );
		}


		public void Close() 
		{
			screen.Close();
		}
	}
}
